package com.chang.bootplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.RedisUtil;
import com.chang.bootplus.entity.Evaluate;
import com.chang.bootplus.mapper.EvaluateMapper;
import com.chang.bootplus.po.EvaluateListPO;
import com.chang.bootplus.po.EvaluatePO;
import com.chang.bootplus.po.LoveNumPO;
import com.chang.bootplus.po.LovePO;
import com.chang.bootplus.service.EvaluateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.bootplus.service.MatrixUserService;

import com.chang.bootplus.vo.EvaluateVO;
import com.chang.bootplus.vo.LoveVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chang
 * @since 2022-01-06
 */
@Service
public class EvaluateServiceImp extends ServiceImpl<EvaluateMapper, Evaluate> implements EvaluateService {


    @Autowired
    MatrixUserService userService;


    @Autowired
    RedisUtil redisUtil;

    @Override
    public ApiResponse<Void> comment(EvaluatePO po) {
        boolean save = save(BeanUtil.beanA2beanB(po, Evaluate.class));
        if (!save){
            throw new BusException("发布评论失败");
        }
        return new ApiResponse<>();
    }

    @Override
    public ApiResponse<EvaluateVO> listComment(EvaluateListPO po) {
        // 根据当前的pid查所有评论
        Page<Evaluate> pages = new Page<>(po.getPageNumber(), po.getPageSize());
        List<Evaluate> alllist = BeanUtil.listA2ListB(pages.getRecords(), Evaluate.class);

        // 将父评论按照时间排序
        Page<Evaluate> page = page(pages, new LambdaQueryWrapper<Evaluate>().eq(Evaluate::getParentId, 0).eq(Evaluate::getPid, po.getPid())
                .orderByAsc(Evaluate::getGmtCreate));
        List<EvaluateVO> fatherVo= BeanUtil.listA2ListB(page.getRecords(), EvaluateVO.class);
        System.out.println(fatherVo);

        List<EvaluateVO> fatherVOS = new  LinkedList<>();
        // 获取到所有的父评论（有对应的userid，对应的backid=0）获取到所有子评论
        fatherVo.stream().forEach(t->{
            List<Evaluate> list = list(new LambdaQueryWrapper<Evaluate>().eq(Evaluate::getParentId, t.getId()));
            // 将子评论转化成VO并存至VO子数组中
            LinkedList<EvaluateVO> chilredVo = new LinkedList<>();
            list.stream().forEach(t1->{
                EvaluateVO evaluateVO = new EvaluateVO();
                String backname=t.getBackId()==null? null:userService.getById(t.getBackId()).getUsername();
                evaluateVO.setId(t1.getId()).setMessage(t1.getMessage())
                        .setUserId(t1.getUserId()).setUsername( userService.getById(t1.getUserId()).getUsername())
                        .setAvatar(userService.getById(t1.getUserId()).getAvatar())
                        .setGrade(t1.getGrade()).setLovenum(t1.getLovenum()).setLovestatus(t1.getLovestatus())
                        .setBackname(backname).setChildrenlist(null).setGmtCreate(t1.getGmtCreate());

                chilredVo.add(evaluateVO);
            });
            List<EvaluateVO> chilrenVOList = chilredVo.stream().sorted(Comparator.comparing(EvaluateVO::getGmtCreate).reversed()).collect(Collectors.toList());

            // 父VO
            EvaluateVO evaluateVO = new EvaluateVO();
            String backname=t.getBackId()==null? null:userService.getById(t.getBackId()).getUsername();
            evaluateVO.setId(t.getId()).setMessage(t.getMessage())
                    .setUserId(t.getUserId()).setUsername( userService.getById(t.getUserId()).getUsername())
                    .setAvatar(userService.getById(t.getUserId()).getAvatar())
                    .setGrade(t.getGrade()).setLovenum(t.getLovenum()).setLovestatus(t.getLovestatus())
                    .setBackname(backname).setChildrenlist(chilrenVOList).setGmtCreate(t.getGmtCreate());

            fatherVOS.add(evaluateVO);
        });
        List<EvaluateVO> collect = fatherVOS.stream().sorted(Comparator.comparing(EvaluateVO::getGmtCreate).reversed()).collect(Collectors.toList());
        return new ApiResponse(fatherVOS,page.getTotal());
    }


    @Override
    public ApiResponse<Void> loveComment(LovePO po) {
        Long evaluateId = po.getEvaluateId();
        String key="like:"+evaluateId;
        Set<Object> values = redisUtil.sGet(key);
        System.out.println(values);
        if (redisUtil.sHasKey(key,new Long(po.getUserId()))){
            redisUtil.setRemove(key,po.getUserId());
            HashMap<String, Integer> map = new HashMap<>();
            map.put("status",0);
            return new ApiResponse().setReMsg("用户"+po.getUserId()+"取消点赞").setBody(map);
        }
        HashMap<String, Integer> map = new HashMap<>();
        map.put("status",1);
        redisUtil.sSet(key,new Long(po.getUserId()));
        return new ApiResponse().setReMsg("用户"+po.getUserId()+"点赞").setBody(map);
    }

    @Override
    public ApiResponse<Void> deleteComment(EvaluateListPO po) {
        Evaluate one = getById(po.getId());
        if (one==null){
            throw new BusException("评论不存在");
        }
        removeById(po.getId());
        return new ApiResponse<>();
    }

    @Override
    public ApiResponse<Void> backComment(EvaluatePO po) {
        Evaluate evaluate = BeanUtil.beanA2beanB(po, Evaluate.class);
        evaluate.setLovenum(0L);
        save(evaluate);
        return new ApiResponse<>();
    }

    @Override
    public ApiResponse<LoveVO> getLoveNum(LoveNumPO po) {
        Long evaluateId = po.getEvaluateId();
        String key="like:"+evaluateId;
        Set<Object> values = redisUtil.sGet(key);
        return new ApiResponse<>(new LoveVO().setLovenum(new Long(values.size())));
    }


}
